var mosca = require('mosca');
var amqp = require('amqp');
var crypto = require('crypto');

var RANDOM_LEN = 10;

var ascoltatore = {
  type: 'amqp',
  json: false,
  amqp: amqp,
  client: amqp.createConnection({ host: 'localhost' }),
  exchange: 'makeblock-iot-topics'
};

var port = 8080;

var moscaSettings = {
  port: port,
  backend: ascoltatore,
  http: {
    port: 1884,
    bundle: true,
    static: './'
  }
};

var authenticate = function(client, username, password, callback) {
  console.log('authenticate');
  var authorized = (username === 'makeblockiot' && password.toString() === 'makeiotblock');
  if (authorized) {
    client.user = username;
  }
  callback(null, authorized);
}

// var authorizePublish = function(client, topic, payload, callback) {
//   console.log('authorizePublish');
//   callback(null, client.user == topic.split('/')[1]);
// }

// var authorizeSubscribe = function(client, topic, callback) {
//   console.log('authorizeSubscribe');
//   callback(null, client.user == topic.split('/')[1]);
// }

var _genRandomString = function(callback) {
  crypto.randomBytes(RANDOM_LEN, (err, buf) => {
    if (err) {
      return callback(err);
    }
    return callback(null, buf.toString('base64'));
  });
};

var _genUserKey = function(id) {
  var cipher = crypto.createCipher('aes192', 'makeblock-shenjingyuan-iot');
    _genRandomString(function(err, str) {
      var encrypted = cipher.update(id + '/' + str, 'utf8', 'hex');
      encrypted += cipher.final('hex');
      console.log(encrypted);
      return encrypted;
    });
};

var _decodeUserKey = function(key) {
  var decipher = crypto.createDecipher('aes192', 'makeblock-shenjingyuan-iot');
  var encrypted = key;
  var ok = false;
  var decrypted;
  try {
    decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    console.log(decrypted);
    console.log(parseInt(decrypted.split('/')[0]));
    // parseInt(decrypted.split('/')[0]);
    ok = true;
  } catch(e) {
    ok = false;
    console.log('_decodeUserKey failed');
  }
  return ok;
};

function runServer() {
  var server = new mosca.Server(moscaSettings);
  server.on('ready', setup);

  server.on('clientConnected', function(client) {
    console.log('connected, clientId:' + client.id);
  });

  // fired when a message is received
  server.on('published', function(packet, client) {
    if (client){
      console.log('Received Topic Publish Message: ', packet.topic, packet.payload.toString());
    }
    
  });

  // fired when the mqtt server is ready
  function setup() {
    server.authenticate = authenticate;
    // server.authorizePublish = authorizePublish;
    // server.authorizeSubscribe = authorizeSubscribe;
    console.log('mqtt broker is up and running on port ' + port);
    // _genUserKey(9);
    // _decodeUserKey('ca77ae9a73c5b27d765b609eef3240bc3fb88b249e1e7223e8e6e0bcc57c894d');
    _decodeUserKey('shansjlinyanwenhuangyanwen');
  }

  // add websocket support
}

exports.runServer = runServer;
